/**
 * @(#)SimulatorOnlineTask.java 2017年5月25日
 * Copyright(C) 2017年5月25日 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.task;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.jsbd.boss.common.BaseThread;
import org.jsbd.boss.service.IEmailSendService;
import org.jsbd.boss.service.SimulatorManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 模拟器在线数监控
 * @author <a href="mailto:zhouchao@zhexinit.com" >周超</a>
 * @version 1.0.0
 */
public class SimulatorOnlineTask extends BaseThread{
	
	public static final Logger LOGGER = LoggerFactory.getLogger(SimulatorOnlineTask.class);

	@Autowired
	private SimulatorManager simulatorManager;
	@Autowired
	private IEmailSendService emailSendService;
	
	private Map<String,Integer> lastMap=new HashMap<String,Integer>();
	
	@Override
	public void start(){
		Map<String,Integer> numMap=simulatorManager.getOnlineSimulatorNum();
		if(lastMap.isEmpty()){
			lastMap.putAll(numMap);
			return;
		}
		
		//总的模拟器进行比较
		Integer lastTotalNum=lastMap.get("totalNum");
		if(lastTotalNum==null){
			lastTotalNum=0;
		}
		
		Integer totalNum=numMap.get("totalNum");
		if(totalNum==null){
			totalNum=0;
		}
		
		if(lastTotalNum<=totalNum){
			lastMap.putAll(numMap);
			return;
		}
		
		//如果超过一定比例就报警
		double rate=(lastTotalNum-totalNum)/lastTotalNum;
		if(rate<0.01){
			lastMap.putAll(numMap);
			return;
		}
		
		StringBuffer content=new StringBuffer();
		String template="<span style='color:red'>版本{sysVer}:减少了{num}模拟器，当前模拟器数为{currentNum}，请注意</span>";
		lastMap.remove("totalNum");
		for(Entry<String, Integer> entity:lastMap.entrySet()){
			String sysVer=entity.getKey();
			Integer lastNum=entity.getValue();
			Integer num=numMap.get(sysVer);
			if(num==null){
				num=0;
			}
			
			content.append(template.replace("{sysVer}", sysVer)
					.replace("{num}", (lastNum-num)+"")
					.replace("{currentNum}",num+"")).append("\r\n");
		}
		
		lastMap.putAll(numMap);
		
		try{
			emailSendService.sendEmailToSysAccount("模拟器在线点击", content.toString(), null);
		}catch(Exception e){
			 LOGGER.error("邮件发送失败",e);
		}
		
	}
	
}
